package org.sundy.net.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server {

	private ServerSocketChannel serverSocketChannel;
	
	private Logger log = Logger.getLogger(Server.class.getName()) ;
	
	public Server(){
		this.log.setLevel(Level.INFO) ;
	}

	public void start() {
		try {
			Selector selector = Selector.open();
			ServerSocketChannel serverSocketChannel = ServerSocketChannel.open() ;
			serverSocketChannel.configureBlocking(false) ;
			ServerSocket serverSocket = serverSocketChannel.socket() ;
			InetSocketAddress socketAddress = new InetSocketAddress(55555) ;
			serverSocket.bind(socketAddress);
			serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT) ;
			log.info("port register finished!") ;
			while(true){
				selector.select() ;
				Set<SelectionKey> selectionKeys = selector.selectedKeys();
				Iterator<SelectionKey> iter = selectionKeys.iterator() ;
				ByteBuffer byteBuffer = ByteBuffer.allocate(20) ;
				SocketChannel socketChannel ;
				while(iter.hasNext()){
					SelectionKey key = iter.next() ;
					if((key.readyOps() & SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT){
						ServerSocketChannel subssc = (ServerSocketChannel)key.channel() ;
						socketChannel = subssc.accept() ;
						socketChannel.configureBlocking(false) ;
						socketChannel.register(selector, SelectionKey.OP_READ) ;
						iter.remove() ;
						log.info("has new connector "+ socketChannel) ;
					}else if((key.readyOps() & SelectionKey.OP_READ)==SelectionKey.OP_READ){
						socketChannel =(SocketChannel)key.channel() ;
						while(true){
							byteBuffer.clear() ;
							int a ;
							try{
								a = socketChannel.read(byteBuffer) ;
							}catch(IOException ex){
								ex.printStackTrace() ;
								break ;
							}
							if(-1==a)break ;
							if(a>0){
								byte[] b = byteBuffer.array() ;
								log.info("receive data: "+new String(b)) ;
								byteBuffer.flip() ;
								socketChannel.write(byteBuffer) ;
								log.info("send "+new String(b)) ;
							}
						}
						socketChannel.close() ;
						log.info("connector finished!") ;
						iter.remove() ;
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}










































































